const fs = require('fs');
const cheerio = require('cheerio');
const request = require('../../config/http');
const Model = require('../../mongo/Model/Novel');
const _ = require('lodash');

const tyxsFN = ({ title, page, novelURL }, ManML, res) => {
  const style = `<style>
    html,body{
      height:100%;
      display:flex;
      justify-content: center;
    }
    h1 {
      margin-bottom: 12px;
      text-align: center;
      display: block;
      width: 100%;
      font-weight: 900;
    }
    .bottem1{
      display:none
    }
    .lm{
      display:none
    }
    p{
      display:none
    }
    .box{
      width:500px;
      height:100%;
    }
  </style>`;

  Model.findOne({ title }).then((ret) => {
    const novelConfig = ret.novelConfig;
    if (!_.isEmpty(novelConfig)) {
      if (!fs.existsSync(ManML)) {
        fs.mkdir(ManML, (err) => err);
      }
      if (page === 'all') {
        novelConfig.forEach((val) => {
          const ML = `${ManML}`;
          const URL = val.URL;
          const URLisArray = Array.isArray(URL);
          if (!fs.existsSync(ML)) {
            fs.mkdir(ML, (err) => err);
          }
          if (URLisArray) {
            URL.forEach(async (url, key) => {
              const res = await request.get(url);
              const $ = cheerio.load(res, { decodeEntities: false });
              const titleText = $('.bookname').html();
              const content = $('#content').html();
              const $title = cheerio.load(titleText, { decodeEntities: false });
              const name = $title('h1').html();
              const ChapterName = name.split(' ')[1];
              let introduceName = name.split(' ')[2];
              if (introduceName.split('(').length === 1) {
                introduceName = introduceName.split('（')[0];
              } else {
                introduceName = introduceName.split('(')[0];
              }
              const MLIntroduce = `${ML}/${ChapterName + '  ' + introduceName}`;
              if (!fs.existsSync(MLIntroduce)) {
                fs.mkdir(MLIntroduce, (err) => err);
              }
              fs.writeFile(
                `${MLIntroduce}/${name}.html`,
                style +
                  '<div class="box">' +
                  titleText +
                  content +
                  '<br/></div>',
                (err) => err
              );
            });
          } else {
            request.get(URL).then((res) => {
              const $ = cheerio.load(res, { decodeEntities: false });
              const titleText = $('.bookname').html();
              const content = $('#content').html();
              const $title = cheerio.load(titleText, { decodeEntities: false });
              const name = $title('h1').html();
              const ChapterName = name.split(' ')[1];
              let introduceName = name.split(' ')[2];
              if (introduceName.split('(').length === 1) {
                introduceName = introduceName.split('（')[0];
              } else {
                introduceName = introduceName.split('(')[0];
              }
              const MLIntroduce = `${ML}/${ChapterName + '  ' + introduceName}`;
              if (!fs.existsSync(MLIntroduce)) {
                fs.mkdir(MLIntroduce, (err) => err);
              }
              fs.writeFile(
                `${MLIntroduce}/${name}.html`,
                style +
                  '<div class="box">' +
                  titleText +
                  content +
                  '<br/></div>',
                (err) => err
              );
            });
          }
        });
      } else {
        let URLNovel = null;
        novelConfig.forEach((val) => {
          if (val.page === page) {
            URLNovel = val;
            return;
          }
        });
        if (!URLNovel) {
          let novelPages = 0;
          novelConfig.forEach((val) => {
            if (val.page > novelPages) {
              novelPages = val.page;
            }
          });
          res.send({
            code: 1,
            message: `数据库中目前还没有第${page}章,最近更新到了第${novelPages}章!!!`,
          });
          return;
        }
        const URL = URLNovel.URL;
        const URLisArray = Array.isArray(URL);
        const ML = `${ManML}`;

        if (!fs.existsSync(ML)) {
          fs.mkdir(ML, (err) => err);
        }

        if (URLisArray) {
          URL.forEach((url, key) => {
            request.get(url).then((res) => {
              const $ = cheerio.load(res, { decodeEntities: false });
              const titleText = $('.bookname').html();
              const content = $('#content').html();
              const $title = cheerio.load(titleText, { decodeEntities: false });
              const name = $title('h1').html();
              const ChapterName = name.split(' ')[1];
              let introduceName = name.split(' ')[2];
              if (introduceName.split('(').length === 1) {
                introduceName = introduceName.split('（')[0];
              } else {
                introduceName = introduceName.split('(')[0];
              }
              const MLIntroduce = `${ML}/${ChapterName + '  ' + introduceName}`;
              if (!fs.existsSync(MLIntroduce)) {
                fs.mkdir(MLIntroduce, (err) => err);
              }

              fs.writeFile(
                `${MLIntroduce}/${name}.html`,
                style +
                  '<div class="box">' +
                  titleText +
                  content +
                  '<br/></div>',
                (err) => err
              );
            });
          });
        } else {
          request.get(URL).then((res) => {
            const $ = cheerio.load(res, { decodeEntities: false });
            const titleText = $('.bookname').html();
            const content = $('#content').html();
            const $title = cheerio.load(titleText, { decodeEntities: false });
            const name = $title('h1').html();
            const ChapterName = name.split(' ')[1];
            let introduceName = name.split(' ')[2];
            if (introduceName.split('(').length === 1) {
              introduceName = introduceName.split('（')[0];
            } else {
              introduceName = introduceName.split('(')[0];
            }
            const MLIntroduce = `${ML}/${ChapterName + '  ' + introduceName}`;
            if (!fs.existsSync(MLIntroduce)) {
              fs.mkdir(MLIntroduce, (err) => err);
            }
            fs.writeFile(
              `${MLIntroduce}/${name}.html`,
              style + '<div class="box">' + titleText + content + '<br/></div>',
              (err) => err
            );
          });
        }
      }
      res.send({
        code: 0,
        message: `以爬取 ${title} 到 ${novelURL} 目录中`,
      });
    } else {
      res.send({
        code: 1,
        message: '数据库中暂时没有该小说,请联系管理员!!!',
        data: Object.keys(novelConfig),
      });
    }
  });
};

module.exports = tyxsFN;
